import { Toast, Modal } from "antd-mobile";
import { Component } from "react";
import { Link } from "react-router-dom";
import HouseItem from "../../components/HouseItem";
import NavHeader from '../../components/NavHeader'
import NoHouse from "../../components/NoHouse";
import { API } from "../../utils/api";

import styles from './index.module.css'

export default class Rent extends Component {
  state = {
    houseList: []
  }

  getHouseList = async () => {
    Toast.loading('数据加载中...', 0)
    let res = await API('/user/houses')
    Toast.hide()
    if (res.status === 200) {
      this.setState({
        houseList: res.data.body
      })
    } else {
      Toast.fail(res.data.description)
    }
  }

  onEdit = async (house) => {
    const { houseCode } = house
    let res = await API.get(`/houses/${houseCode}`)
    if (res.status === 200) {
      this.props.history.push('/rent/add', {
        house: res.data.body
      })
    } else {
      Toast.info(res.data.description)
    }
  }

  onDelete = (house) => {
    const { houseCode } = house
    Modal.alert('提示', '确认删除发布房源?', [
      { text: '取消'},
      {
        text: '确定',
        onPress: async () => {
          Toast.info('房源删除', 0)
          let res = await API.patch(`/user/houses/${houseCode}`, {
            shelf: 'true'
          })
          Toast.hide()
          if (res.status === 200) {
            this.getHouseList()
          } else {
            Toast.fail(res.data.description)
          }
        }
      },
    ])
  }

  renderHouseList = () => {
    const { houseList } = this.state

    if (houseList && houseList.length) {
      return (
        houseList.map(item => {
          return <HouseItem key={item.houseCode} house={item} editable={true} onClick={(house) => {this.props.history.push(`/detail/${house.houseCode}`);}} onEdit={this.onEdit}  onDelete={this.onDelete}></HouseItem>
        }) 
      )
    } else {
      return (
        <NoHouse>
          您还没有发布房源，
          <Link to="/rent/add" className={styles.link}>
            去发布房源
          </Link>
          吧~
        </NoHouse>
      )
    }

  }

  componentDidMount() {
    this.getHouseList()
  }

  render() {
    return (
      <div className={styles.rent}>
        <NavHeader>我发布的房源</NavHeader>
        <div className={styles.houseList}>
          {
            this.renderHouseList()
          }
        </div>
      </div>
    )
  }
}